<script setup>
import { ref } from 'vue'
import {
  articleAddChannelService,
  articleEditChannelService
} from '@/api/article'
import { ElMessage } from 'element-plus'
const dialogVisible = ref(false)
const formList = ref({
  cate_name: '',
  cate_alias: ''
})
const rules = {
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ]
}
const form = ref(null)

const openDialog = (row) => {
  dialogVisible.value = true
  formList.value = { ...row }
  //   console.log(formList.value)
}
// 暴露给父组件的方法
defineExpose({
  openDialog
})

const emit = defineEmits(['refresh'])
const onSubmit = async () => {
  // 等待表单验证成功
  await form.value.validate()
  //   console.log(formList.value)
  if (formList.value.id) {
    // 编辑
    await articleEditChannelService(formList.value)
    ElMessage.success('编辑成功')
  } else {
    // 新增
    await articleAddChannelService(formList.value)
    ElMessage.success('新增成功')
  }
  // 关闭弹窗
  dialogVisible.value = false
  // 通知父组件刷新表格
  emit('refresh')
}
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formList.id ? '编辑分类' : '新增分类'"
    width="500"
  >
    <el-form :model="formList" :rules="rules" ref="form">
      <el-form-item label="分类名称" prop="cate_name">
        <el-input
          v-model="formList.cate_name"
          placeholder="请输入分类名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input
          v-model="formList.cate_alias"
          placeholder="请输入分类别名"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
